﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using MiniJSON;
using UnityEngine.UI;

public class SpriteInfo
{
    public string name;
    public string path;
    public Rect rect;
}

public class Group
{
    public string name;
    public List<SpriteInfo> spritesInfo = new List<SpriteInfo>();
}

public class LayersLoaderWithGroup : MonoBehaviour
{
    public TextAsset psdJson;
    public Transform psdParent;
    public float basePixelWidth = 1536;
    public float basePixelHeight = 2268;

    public void BuildLayers()
    {
#if UNITY_EDITOR
        print("buildingLayers...");
        string path = AssetDatabase.GetAssetPath(psdJson);
        DirectoryInfo directoryInfo = new DirectoryInfo(path);
        string parentPath = directoryInfo.Parent.ToString();
        LoadTemplatePsdJson(psdJson.text, out List<Group> groupList);
        GameObject root = new GameObject();
        root.transform.SetParent(psdParent);
        root.transform.localPosition = Vector3.zero;
        root.name = Path.GetFileNameWithoutExtension(path);
        int layers = 0;
        foreach (var group in groupList)
        {
            //Create group object
            GameObject groupObject = new GameObject(group.name);
            groupObject.transform.SetParent(root.transform);
            group.spritesInfo.Reverse();
            foreach (var sprite in group.spritesInfo)
            {
                string loadPath = Path.Combine(parentPath, sprite.path);
                string assetsPath = loadPath.Split(new string[] { "Assets" }, System.StringSplitOptions.None)[1];
                assetsPath = "Assets" + assetsPath;
                Sprite sp = AssetDatabase.LoadAssetAtPath<Sprite>(assetsPath + ".png");
                GameObject spriteObj = new GameObject(sprite.name);
                spriteObj.transform.SetParent(groupObject.transform);
                spriteObj.transform.localPosition = new Vector3(-basePixelWidth / 200f + sprite.rect.x / 100f, -basePixelHeight / 200f + sprite.rect.y / 100f, 0);
                //spriteObj.transform.SetAsFirstSibling();
                SpriteRenderer sr = spriteObj.AddComponent<SpriteRenderer>();
                sr.sprite = sp;
                sr.sortingOrder = layers;
                layers++;
            }
        }
        print("Done!...");
#endif
    }


    private void LoadTemplatePsdJson(string psdJsonText,
                                     out List<Group> groupList)
    {

        groupList = new List<Group>();
        //解析为字典
        Dictionary<string, object> psdInfoDictionary = Json.Deserialize(psdJsonText) as Dictionary<string, object>;

        //进一步解析出“skins”字典
        Dictionary<string, object> skinsInfoDictionary = psdInfoDictionary["skins"] as Dictionary<string, object>;
        foreach (string skin in skinsInfoDictionary.Keys)
        {
            if (skin.Equals("default"))
                continue;
            var groupObj = skinsInfoDictionary[skin] as Dictionary<string, object>;
            Group group = new Group();
            group.name = skin;
            //parse group
            foreach (string key in groupObj.Keys)
            {
                var sprites = groupObj[key] as Dictionary<string, object>;
                SpriteInfo spInfo = new SpriteInfo();
                spInfo.name = key;
                foreach (string spriteKey in sprites.Keys)
                {
                    var pngInfoDictionary = sprites[spriteKey] as Dictionary<string, object>;
                    spInfo.path = pngInfoDictionary["name"].ToString();
                    Rect pngPixelRect = new Rect
                    {
                        x = float.Parse(pngInfoDictionary["x"].ToString()),
                        y = float.Parse(pngInfoDictionary["y"].ToString()),
                        width = float.Parse(pngInfoDictionary["width"].ToString()),
                        height = float.Parse(pngInfoDictionary["height"].ToString())
                    };
                    spInfo.rect = pngPixelRect;
                    group.spritesInfo.Add(spInfo);
                }
            }
            groupList.Add(group);
        }
        return;
    }
}
